package com.fiberhome.nas.core.util.media

import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import android.provider.MediaStore.Files.FileColumns
import android.provider.MediaStore.MediaColumns
import com.fiberhome.nas.core.model.entity.LocalAlbum
import com.fiberhome.nas.core.model.entity.LocalMediaItem
import com.fiberhome.nas.core.model.entity.MediaType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.Date

class MediaUtils(private val context: Context) {
    private val contentResolver: ContentResolver = context.contentResolver

    /**
     * 获取所有相册，包括系统相册和自定义相册
     */
    suspend fun getAllAlbums(): List<LocalAlbum> = withContext(Dispatchers.IO) {
        val albums = mutableListOf<LocalAlbum>()
        val albumMap = mutableMapOf<String, LocalAlbum>()
        // 新增: 用于统计所有媒体的变量
        var totalPhotoCount = 0
        var totalVideoCount = 0
        var latestMediaUri: Uri? = null
        var latestMediaDate: Date? = null

        val projection = arrayOf(
            FileColumns.BUCKET_ID,
            FileColumns.BUCKET_DISPLAY_NAME,
            FileColumns.MEDIA_TYPE,
            MediaColumns.DATE_MODIFIED,
            MediaColumns._ID
        )
        val selection = "${FileColumns.MEDIA_TYPE} IN (?, ?)"
        val selectionArgs = arrayOf(
            FileColumns.MEDIA_TYPE_IMAGE.toString(),
            FileColumns.MEDIA_TYPE_VIDEO.toString()
        )
        val sortOrder = "${MediaColumns.DATE_MODIFIED} DESC"

        contentResolver.query(
            MediaStore.Files.getContentUri("external"),
            projection,
            selection,
            selectionArgs,
            sortOrder
        )?.use { cursor ->
            val bucketIdColumn = cursor.getColumnIndexOrThrow(FileColumns.BUCKET_ID)
            val bucketNameColumn = cursor.getColumnIndexOrThrow(FileColumns.BUCKET_DISPLAY_NAME)
            val dateModifiedColumn = cursor.getColumnIndexOrThrow(MediaColumns.DATE_MODIFIED)
            val mediaTypeColumn = cursor.getColumnIndexOrThrow(FileColumns.MEDIA_TYPE)
            val idColumn = cursor.getColumnIndexOrThrow(MediaColumns._ID)

            while (cursor.moveToNext()) {
                val bucketId = cursor.getString(bucketIdColumn)
                val bucketName = cursor.getString(bucketNameColumn)
                val mediaId = cursor.getLong(idColumn)
                val dateModified = Date(cursor.getLong(dateModifiedColumn) * 1000)
                val mediaType = cursor.getInt(mediaTypeColumn)
                val uri = Uri.withAppendedPath(
                    MediaStore.Files.getContentUri("external"),
                    mediaId.toString()
                )

                // 更新总媒体计数
                if (mediaType == FileColumns.MEDIA_TYPE_IMAGE) {
                    totalPhotoCount++
                } else if (mediaType == FileColumns.MEDIA_TYPE_VIDEO) {
                    totalVideoCount++
                }

                // 记录最新的媒体文件信息（因为按时间倒序，第一个就是最新的，后续不会更新，但为了保持原逻辑不变，仍然每次比较）
                if (latestMediaDate == null || dateModified.after(latestMediaDate)) {
                    latestMediaDate = dateModified
                    latestMediaUri = uri
                }

                // 更新相册信息
                val currentAlbum = albumMap[bucketId]
                if (currentAlbum == null) {
                    // 创建新相册，初始计数为0
                    val newAlbum = LocalAlbum(
                        bucketId = bucketId,
                        albumName = bucketName ?: "Unknown",
                        coverUri = uri,
                        photoCount = 0,
                        videoCount = 0,
                        lastModified = dateModified
                    )
                    // 根据媒体类型增加计数
                    val updatedAlbum = when (mediaType) {
                        FileColumns.MEDIA_TYPE_IMAGE -> newAlbum.copy(photoCount = 1)
                        FileColumns.MEDIA_TYPE_VIDEO -> newAlbum.copy(videoCount = 1)
                        else -> newAlbum
                    }
                    albumMap[bucketId] = updatedAlbum
                } else {
                    // 更新现有相册的计数
                    val updatedAlbum = when (mediaType) {
                        FileColumns.MEDIA_TYPE_IMAGE -> currentAlbum.copy(photoCount = currentAlbum.photoCount + 1)
                        FileColumns.MEDIA_TYPE_VIDEO -> currentAlbum.copy(videoCount = currentAlbum.videoCount + 1)
                        else -> currentAlbum
                    }
                    // 检查是否需要更新封面和最后修改时间
                    val finalAlbum = if (dateModified.after(updatedAlbum.lastModified)) {
                        updatedAlbum.copy(lastModified = dateModified, coverUri = uri)
                    } else {
                        updatedAlbum
                    }
                    albumMap[bucketId] = finalAlbum
                }
            }
        }

        // 新增: 创建"全部"相册并添加到列表开头
        latestMediaUri?.let {
            latestMediaDate?.let { date ->
                val allMediaAlbum = LocalAlbum(
                    bucketId = DEFAULT_ALBUM_ID, // 特殊ID标识全部媒体
                    albumName = "全部",
                    coverUri = it,
                    photoCount = totalPhotoCount,
                    videoCount = totalVideoCount,
                    lastModified = date
                )
                albums.add(allMediaAlbum)
            }
        }

        albums.addAll(albumMap.values)
        return@withContext albums.sortedByDescending { it.lastModified }
    }

    /**
     * 根据相册ID获取媒体项列表
     * @param bucketId 相册ID
     * @return 媒体项列表
     */
    suspend fun getMediaItemsByAlbum(bucketId: String): List<LocalMediaItem> =
        withContext(Dispatchers.IO) {
            val mediaItems = mutableListOf<LocalMediaItem>()

            val projection = arrayOf(
                MediaColumns._ID,
                MediaColumns.DISPLAY_NAME,
                MediaColumns.MIME_TYPE,
                MediaColumns.DATE_TAKEN,
                MediaColumns.DURATION,
                MediaColumns.SIZE,
                MediaColumns.WIDTH,
                MediaColumns.HEIGHT,
                FileColumns.MEDIA_TYPE,
                MediaColumns.DATA
            )

            // 新增: 根据bucketId判断是否查询全部媒体
            val (selection, selectionArgs) = if (bucketId == DEFAULT_ALBUM_ID) {
                // 查询所有图片和视频
                "${FileColumns.MEDIA_TYPE}=? OR ${FileColumns.MEDIA_TYPE}=?" to arrayOf(
                    FileColumns.MEDIA_TYPE_IMAGE.toString(),
                    FileColumns.MEDIA_TYPE_VIDEO.toString()
                )
            } else {
                // 按原逻辑查询特定相册
                "${FileColumns.BUCKET_ID}=? AND (${FileColumns.MEDIA_TYPE}=? OR ${FileColumns.MEDIA_TYPE}=?)" to arrayOf(
                    bucketId,
                    FileColumns.MEDIA_TYPE_IMAGE.toString(),
                    FileColumns.MEDIA_TYPE_VIDEO.toString()
                )
            }

            val sortOrder = "${MediaColumns.DATE_TAKEN} DESC"

            contentResolver.query(
                MediaStore.Files.getContentUri("external"),
                projection,
                selection,
                selectionArgs,
                sortOrder
            )?.use { cursor ->
                val idColumn = cursor.getColumnIndexOrThrow(MediaColumns._ID)
                val displayNameColumn = cursor.getColumnIndexOrThrow(MediaColumns.DISPLAY_NAME)
                val mimeTypeColumn = cursor.getColumnIndexOrThrow(MediaColumns.MIME_TYPE)
                val dateTakenColumn = cursor.getColumnIndexOrThrow(MediaColumns.DATE_TAKEN)
                val durationColumn = cursor.getColumnIndexOrThrow(MediaColumns.DURATION)
                val sizeColumn = cursor.getColumnIndexOrThrow(MediaColumns.SIZE)
                val widthColumn = cursor.getColumnIndexOrThrow(MediaColumns.WIDTH)
                val heightColumn = cursor.getColumnIndexOrThrow(MediaColumns.HEIGHT)
                val mediaTypeColumn = cursor.getColumnIndexOrThrow(FileColumns.MEDIA_TYPE)
                val dataColumn = cursor.getColumnIndexOrThrow(MediaColumns.DATA)
                while (cursor.moveToNext()) {
                    val id = cursor.getLong(idColumn)
                    val displayName = cursor.getString(displayNameColumn)
                    val mimeType = cursor.getString(mimeTypeColumn)
                    val dateTaken = Date(cursor.getLong(dateTakenColumn))
                    val duration =
                        if (!cursor.isNull(durationColumn)) cursor.getLong(durationColumn) else null
                    val fileSize = cursor.getLong(sizeColumn)
                    val width = cursor.getInt(widthColumn)
                    val height = cursor.getInt(heightColumn)
                    val mediaType = cursor.getInt(mediaTypeColumn)
                    val data = cursor.getString(dataColumn)

                    val uri = Uri.withAppendedPath(
                        MediaStore.Files.getContentUri("external"),
                        id.toString()
                    )

                    val type = if (mediaType == FileColumns.MEDIA_TYPE_IMAGE) {
                        MediaType.PHOTO
                    } else {
                        MediaType.VIDEO
                    }

                    mediaItems.add(
                        LocalMediaItem(
                            id = id,
                            uri = uri,
                            type = type,
                            displayName = displayName,
                            mimeType = mimeType,
                            dateTaken = dateTaken,
                            duration = duration,
                            fileSize = fileSize,
                            width = width,
                            height = height,
                            path = data
                        )
                    )
                }
            }

            return@withContext mediaItems
        }

    companion object {
        const val DEFAULT_ALBUM_ID = "all_media"

        // 单例模式（可选，根据项目依赖注入策略调整）
        @SuppressLint("StaticFieldLeak")
        @Volatile
        private var instance: MediaUtils? = null

        fun getInstance(context: Context): MediaUtils {
            return instance ?: synchronized(this) {
                instance ?: MediaUtils(context.applicationContext).also {
                    instance = it
                }
            }
        }
    }
}